package com.xbao.core.util;

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

public class DateUtil {

    /**
     * 将时间字符串转换成日期类型（精确度：秒）
     *
     * @return Date
     */


    public static int getAge(long birthDaylong) {
        Date birthDay = new Date(birthDaylong);
        Calendar cal = Calendar.getInstance();

        if (cal.before(birthDay)) {
            throw new IllegalArgumentException(
                    "The birthDay is before Now.It's unbelievable!");
        }
        int yearNow = cal.get(Calendar.YEAR);
        int monthNow = cal.get(Calendar.MONTH);
        int dayOfMonthNow = cal.get(Calendar.DAY_OF_MONTH);
        cal.setTime(birthDay);

        int yearBirth = cal.get(Calendar.YEAR);
        int monthBirth = cal.get(Calendar.MONTH);
        int dayOfMonthBirth = cal.get(Calendar.DAY_OF_MONTH);

        int age = yearNow - yearBirth;

        if (monthNow <= monthBirth) {
            if (monthNow == monthBirth) {
                if (dayOfMonthNow < dayOfMonthBirth) age--;
            } else {
                age--;
            }
        }
        return age;
    }


    public static Date getDateByString(String time, String formate) {
        Date date = null;
        SimpleDateFormat formatter = new SimpleDateFormat(formate);
        try {
            date = formatter.parse(time);
        } catch (Exception e) {
            System.out.println("error --StringUtil.getDateByString   ");
        }
        return date;
    }

    public static int getDayByDateStr(String time) {
        Calendar calendar = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        try {
            calendar.setTime(sdf.parse(time));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        int i = calendar.get(Calendar.DAY_OF_WEEK);
        if (i == 1) {
            return 7;
        } else {
            return i - 1;
        }
    }


    /**
     * 将时间字符串转换成日期类型（精确度：秒）
     *
     * @param time
     * @return Date
     */

    public static Date getDateByString(String time) {
        Date date = null;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            date = formatter.parse(time);
        } catch (Exception e) {
            System.out.println("error --StringUtil.getDateByString   ");
        }
        return date;
    }

    public static Date getDateTimeByTime(Long time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String d = format.format(time);
        Date date = null;
        try {
            date = format.parse(d);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date;
    }


    public static String getDateStringByTime(Long time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        String d = format.format(time);
        Date date = null;
        try {
            date = format.parse(d);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return format.format(date);
    }


    public static Long getDateByTime(Long time) {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        String d = format.format(time);
        Date date = null;
        try {
            date = format.parse(d);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return date.getTime();
    }


    public static int daysBetween(Date smdate, Date bdate) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        smdate = sdf.parse(sdf.format(smdate));
        bdate = sdf.parse(sdf.format(bdate));
        Calendar cal = Calendar.getInstance();
        cal.setTime(smdate);
        long time1 = cal.getTimeInMillis();
        cal.setTime(bdate);
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);

        return Integer.parseInt(String.valueOf(between_days));
    }

    /**
     * 字符串的日期格式的计算
     */
    public static int daysBetween(String smdate, String bdate) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar cal = Calendar.getInstance();
        try {
            cal.setTime(sdf.parse(smdate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long time1 = cal.getTimeInMillis();
        try {
            cal.setTime(sdf.parse(bdate));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        long time2 = cal.getTimeInMillis();
        long between_days = (time2 - time1) / (1000 * 3600 * 24);

        return Integer.parseInt(String.valueOf(between_days));
    }

    /**
     * 将时间字符串转换成日期类型（精确度：日）
     *
     * @param time
     * @return
     */
    public static Date getDayByString(String time) {
        Date date = null;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        try {
            date = formatter.parse(time);
        } catch (Exception e) {
            System.out.println("error --StringUtil.getDateByString   ");
        }
        return date;
    }

    /**
     * 将日期字符串转换成 "yyyy-MM-dd HH:mm:ss" 字符串
     *
     * @param time
     * @return String
     */
    public static String getStringDateByStringDate(String time) {
        Date date = getDateByString(time);
        String datestr = null;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            datestr = formatter.format(date);
        } catch (Exception e) {
            System.out.println("error --StringUtil.getDateByString   ");
        }
        return datestr;
    }

    /**
     * 将日前数值转换成字符串
     *
     * @param date
     * @return String
     */
    public static String getStringDateByDate(Date date) {
        String datestr = null;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        try {
            datestr = formatter.format(date);
        } catch (Exception e) {
            System.out.println("error --StringUtil.getDateByString   ");
        }
        return datestr;
    }

    public static String now() {
        return getStringDateByDate(new Date());
    }

    /**
     * 将时间字符串累加一天
     *
     * @param time
     * @return String
     */
    public static String getStringDayAddDay(String time) {
        Date date = null;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        try {
            date = formatter.parse(time);
        } catch (Exception e) {
            System.out.println("error --StringUtil.getDateByMoreDay   ");
        }
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.DATE, 1); // 日期分钟加1,Calendar.DATE(天),Calendar.HOUR(小时)
        date = c.getTime(); // 结果
        String str = formatter.format(date);
        return str;

    }

    /**
     * 将时间转成到天的时间字符串
     *
     * @param date
     * @return String
     */
    public static String getStringDayByDate(Date date) {
        String datestr = null;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        datestr = formatter.format(date);
        return datestr;
    }

    /**
     * 将时间转成到天的时间字符串
     *
     * @param date
     * @return String
     */
    public static long getStringDayByDate(String date) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        long time = 0;
        try {
            time = formatter.parse(date).getTime();
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return time;
    }

    /**
     * 将时间转成到天的时间字符串
     *
     * @param date
     * @return String
     */
    public static String getStringDayByDate3(Date date) {
        String datestr = null;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
        datestr = formatter.format(date);
        return datestr;
    }

    /**
     * 将时间转成到天的时间字符串
     *
     * @param date
     * @return String
     */
    public static String getStringDayByDate2(Date date) {
        String datestr = null;
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
        datestr = formatter.format(date);
        return datestr;
    }

    public static Date timestampToDate(Long tt) {
        return new Date(tt);
    }

    /**
     * 将时间对象转换成时间戳对象
     *
     * @param date
     * @return Timestamp
     */
    public static Timestamp getTimestampByDate(Date date) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Timestamp ts = Timestamp.valueOf(sf.format(date));
        return ts;
    }

    public static Long getTimeStampByDate(Date date) {
        Timestamp time = getTimestampByDate(date);
        return time.getTime();
    }


    /**
     * 时间戳对象转成成字符串
     *
     * @param stamp
     * @return String
     */

    public static String getStringDateByTimestamp(Timestamp stamp) {
        SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String ts = sf.format(stamp);
        return ts;
    }


    /**
     * 获取加一个月时间的数据
     *
     * @param date
     * @return
     */
    public static String addOneMonthDay(Date date) {
        Calendar calender = Calendar.getInstance();
        calender.setTime(date);
        calender.add(Calendar.MONTH, 1);
        Date monthday = calender.getTime();
        return getStringDayByDate(monthday);
    }

    /**
     * 获取加任意天数的日期
     *
     * @param date
     * @param date
     * @return
     */
    public static Date addDays(Date date, long days) {
        long daytime = days * 24 * 60 * 60 * 1000;
        long time = date.getTime();
        long last = time + daytime;
        Date damore = new Date(last);
        return damore;
    }

    /**
     * 将时间戳转换为时间 yyyy-MM-dd HH:mm
     *
     * @param timeStamp
     * @return
     */
    public static String stampToTime(long timeStamp) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm", Locale.CHINA);
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
        Date date = new Date(timeStamp);
        String newTime = formatter.format(date);
        return newTime;
    }

    /**
     * 将时间戳转换为时间 yyyy-MM-dd HH:mm:ss
     *
     * @param timeStamp
     * @return
     */
    public static String stampToDateTime(long timeStamp) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
        Date date = new Date(timeStamp);
        String newTime = formatter.format(date);
        return newTime;
    }

    /**
     * 将时间戳转换为时间 yyyy-MM-dd
     *
     * @param timeStamp
     * @return
     */
    public static String stampToDateTime2(long timeStamp) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        formatter.setTimeZone(TimeZone.getTimeZone("GMT+08:00"));
        Date date = new Date(timeStamp);
        String newTime = formatter.format(date);
        return newTime;
    }

    /**
     * 获取加七天时间的数据
     *
     * @param
     * @return
     */
    public static Long addSevenDay() {
        Calendar calender = Calendar.getInstance();
        calender.add(Calendar.DATE, 7);
        calender.getTimeInMillis();

        return calender.getTimeInMillis();
    }

    public static Long getDayBegin() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.MILLISECOND, 001);
        return cal.getTimeInMillis();
    }

    public static long getDateLongByString(String param) {
        long timeStemp = 0;
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm");
            Date date = simpleDateFormat.parse(param);
            timeStemp = date.getTime();
        } catch (ParseException e) {
            System.out.println("转换日期失败");
            e.printStackTrace();
        }
        return timeStemp;
    }

    public static long getDateLongByString(String param, String pattern) {
        long timeStemp = 0;
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(pattern);
            Date date = simpleDateFormat.parse(param);
            timeStemp = date.getTime();
        } catch (ParseException e) {
            System.out.println("转换日期失败");
            e.printStackTrace();
        }
        return timeStemp;
    }


    public static long getDateLong(String param) {
        long timeStemp = 0;
        try {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Date date = simpleDateFormat.parse(param);
            timeStemp = date.getTime();
        } catch (ParseException e) {
            System.out.println("转换日期失败");
            e.printStackTrace();
        }
        return timeStemp;
    }

    //获得当天24点时间戳
    public static Long getTimesnight() {
        Calendar cal = Calendar.getInstance();
        cal.set(Calendar.HOUR_OF_DAY, 23);
        cal.set(Calendar.SECOND, 59);
        cal.set(Calendar.MINUTE, 59);
        cal.set(Calendar.MILLISECOND, 999);
        return cal.getTimeInMillis();
    }


    public static int getMonth() {
        Calendar calendar = Calendar.getInstance();
        //获得当前时间的月份，月份从0开始所以结果要加1
        int month = calendar.get(Calendar.MONTH) + 1;
        return month;
    }


    public static Date getNextWeekNo(Date date, int weekno) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        int day = calendar.get(Calendar.DAY_OF_WEEK);
        int first = calendar.getFirstDayOfWeek();
        calendar.add(Calendar.DAY_OF_WEEK, first - day + weekno - 1);
        Date d = calendar.getTime();
        return d;
    }

    public static Long getNextWeekNo(Long time, int weekno) {
        Date date = new Date(time);
        Date b = getNextWeekNo(date, weekno);
        return b.getTime();
    }

    public static Long getNextTimeEveryDay(Long begintime, int hour, int minutes) {
        Date date = new Date(begintime);
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minutes);
        calendar.set(Calendar.SECOND,0);
        if (calendar.getTimeInMillis() < begintime)
            calendar.add(Calendar.DAY_OF_YEAR, 0);
        return calendar.getTimeInMillis();
    }

    public static Long getNextTimeEveryWeek(Long begintime, int day, int hour, int minutes) {
        Date date = new Date(begintime);
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.DAY_OF_WEEK, day);
        calendar.set(Calendar.MINUTE, minutes);
        calendar.set(Calendar.SECOND,0);
        if (calendar.getTimeInMillis() < begintime)
            calendar.add(Calendar.WEEK_OF_YEAR, 1);
        return calendar.getTimeInMillis();
    }

    public static Long getNextTimeEveryMonth(Long begintime, int dayOfMonth, int hour, int minutes) {
        Date date = new Date(begintime);
        Calendar calendar = Calendar.getInstance();
        calendar.setFirstDayOfWeek(Calendar.MONDAY);
        calendar.setTime(date);
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
        calendar.set(Calendar.MINUTE, minutes);
        if (calendar.getTimeInMillis() < begintime)
            calendar.add(Calendar.MONTH, 1);
        return calendar.getTimeInMillis();
    }


    public static void main(String[] args) {
        Long ctime = System.currentTimeMillis();
        Long a = getNextTimeEveryMonth(ctime, 31, 12, 20);
        Date date = new Date(a);
        DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String t = df.format(date);
        System.out.println(t);
    }


}
